# 生成AI演示数据的管理命令
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import datetime, timedelta
import random

from assets.models import Asset, AssetCategory, Department, MaintenanceRecord
from assets.models_ai import AssetRecommendation, AssetAnomalyDetection, AssetUtilizationAnalysis


class Command(BaseCommand):
    help = '生成AI功能演示数据'

    def add_arguments(self, parser):
        parser.add_argument(
            '--count',
            type=int,
            default=10,
            help='生成数据的数量'
        )

    def handle(self, *args, **options):
        count = options['count']
        
        self.stdout.write('开始生成AI演示数据...')
        
        # 获取必要的数据
        users = list(User.objects.all())
        assets = list(Asset.objects.all())
        categories = list(AssetCategory.objects.all())
        departments = list(Department.objects.all())
        
        if not users or not assets:
            self.stdout.write(
                self.style.ERROR('请先创建用户和资产数据')
            )
            return
        
        # 生成智能推荐
        self.generate_recommendations(users, assets, categories, departments, count)
        
        # 生成异常检测
        self.generate_anomaly_detections(assets, count)
        
        # 生成利用率分析
        self.generate_utilization_analyses(assets, count)
        
        self.stdout.write(
            self.style.SUCCESS(f'AI演示数据生成完成！')
        )

    def generate_recommendations(self, users, assets, categories, departments, count):
        """生成智能推荐数据"""
        recommendation_types = ['maintenance', 'replacement', 'optimization', 'allocation', 'procurement']
        priorities = ['low', 'medium', 'high', 'urgent']
        
        recommendations_data = [
            {
                'type': 'maintenance',
                'title': '建议对资产 {asset_number} 进行预防性维修',
                'description': '根据使用频率和历史维修记录分析，该资产即将到达维修周期，建议提前安排预防性维修。',
                'confidence': random.uniform(0.7, 0.95),
            },
            {
                'type': 'replacement',
                'title': '建议更换老化资产 {asset_number}',
                'description': '该资产已使用超过预期寿命，维修成本持续上升，建议考虑更换新设备。',
                'confidence': random.uniform(0.6, 0.85),
            },
            {
                'type': 'optimization',
                'title': '优化资产 {asset_number} 的配置',
                'description': '检测到该资产利用率较低，建议重新分配或调整使用方式以提高效率。',
                'confidence': random.uniform(0.65, 0.8),
            },
            {
                'type': 'allocation',
                'title': '建议重新分配资产 {asset_number}',
                'description': '根据部门需求分析，该资产在其他部门可能有更高的使用价值。',
                'confidence': random.uniform(0.7, 0.9),
            },
            {
                'type': 'procurement',
                'title': '建议采购 {category_name} 类资产',
                'description': '根据使用趋势分析，该类别资产需求量增加，建议提前采购以满足业务需求。',
                'confidence': random.uniform(0.75, 0.9),
            },
        ]
        
        created_count = 0
        for i in range(count):
            template = random.choice(recommendations_data)
            asset = random.choice(assets) if template['type'] != 'procurement' else None
            category = random.choice(categories) if template['type'] == 'procurement' else None
            
            title = template['title'].format(
                asset_number=asset.asset_number if asset else '',
                category_name=category.name if category else ''
            )
            
            recommendation = AssetRecommendation.objects.create(
                user=random.choice(users),
                recommendation_type=template['type'],
                title=title,
                description=template['description'],
                asset=asset,
                category=category,
                department=random.choice(departments) if random.random() > 0.5 else None,
                confidence_score=template['confidence'] * 100,
                priority=random.choice(priorities),
                recommendation_data={
                    'analysis_date': timezone.now().isoformat(),
                    'data_points': random.randint(50, 200),
                    'trend': random.choice(['increasing', 'decreasing', 'stable']),
                    'risk_level': random.choice(['low', 'medium', 'high']),
                },
                expires_at=timezone.now() + timedelta(days=random.randint(7, 30)),
            )
            created_count += 1
        
        self.stdout.write(f'生成了 {created_count} 个智能推荐')

    def generate_anomaly_detections(self, assets, count):
        """生成异常检测数据"""
        anomaly_types = [
            'usage_pattern', 'maintenance_frequency', 'cost_anomaly', 
            'location_anomaly', 'status_anomaly', 'performance_degradation'
        ]
        severities = ['low', 'medium', 'high', 'critical']
        algorithms = ['statistical_analysis', 'machine_learning', 'rule_based', 'time_series']
        
        anomaly_descriptions = {
            'usage_pattern': '检测到异常的使用模式，与历史数据存在显著差异',
            'maintenance_frequency': '维修频率异常，超出正常范围',
            'cost_anomaly': '成本支出异常，需要进一步调查',
            'location_anomaly': '资产位置变更频繁，可能存在管理问题',
            'status_anomaly': '资产状态变更异常，需要确认',
            'performance_degradation': '性能指标持续下降，建议检查',
        }
        
        created_count = 0
        for i in range(count):
            asset = random.choice(assets)
            anomaly_type = random.choice(anomaly_types)
            
            anomaly = AssetAnomalyDetection.objects.create(
                asset=asset,
                anomaly_type=anomaly_type,
                severity=random.choice(severities),
                description=anomaly_descriptions[anomaly_type],
                confidence_score=random.uniform(0.6, 0.95),
                detection_algorithm=random.choice(algorithms),
                anomaly_data={
                    'threshold': random.uniform(0.1, 0.9),
                    'actual_value': random.uniform(0.1, 1.0),
                    'historical_average': random.uniform(0.3, 0.7),
                    'deviation_percentage': random.uniform(10, 80),
                },
                detection_parameters={
                    'window_size': random.randint(7, 30),
                    'sensitivity': random.uniform(0.1, 0.9),
                    'min_samples': random.randint(10, 100),
                },
                detected_at=timezone.now() - timedelta(
                    hours=random.randint(1, 72)
                ),
            )
            created_count += 1
        
        self.stdout.write(f'生成了 {created_count} 个异常检测记录')

    def generate_utilization_analyses(self, assets, count):
        """生成利用率分析数据"""
        created_count = 0
        
        for i in range(min(count, len(assets))):
            asset = assets[i]
            
            # 生成分析期间
            end_date = timezone.now()
            start_date = end_date - timedelta(days=30)
            
            # 生成利用率数据
            total_hours = 24 * 30  # 30天
            active_hours = random.uniform(100, 600)
            idle_hours = total_hours - active_hours - random.uniform(10, 50)
            maintenance_hours = random.uniform(5, 30)
            
            utilization_rate = (active_hours / total_hours) * 100
            
            analysis = AssetUtilizationAnalysis.objects.create(
                asset=asset,
                analysis_period_start=start_date,
                analysis_period_end=end_date,
                utilization_rate=utilization_rate,
                idle_time_hours=idle_hours,
                active_time_hours=active_hours,
                maintenance_time_hours=maintenance_hours,
                analysis_data={
                    'peak_usage_hours': [9, 10, 11, 14, 15, 16],
                    'low_usage_hours': [0, 1, 2, 3, 4, 5, 22, 23],
                    'weekly_pattern': {
                        'monday': random.uniform(0.6, 0.9),
                        'tuesday': random.uniform(0.6, 0.9),
                        'wednesday': random.uniform(0.6, 0.9),
                        'thursday': random.uniform(0.6, 0.9),
                        'friday': random.uniform(0.6, 0.9),
                        'saturday': random.uniform(0.2, 0.5),
                        'sunday': random.uniform(0.1, 0.3),
                    },
                    'efficiency_trend': random.choice(['improving', 'declining', 'stable']),
                },
            )
            
            # 生成优化建议
            analysis.generate_suggestions()
            created_count += 1
        
        self.stdout.write(f'生成了 {created_count} 个利用率分析记录')